//
//  ZLPTopicViewController.m
//  TangYi
//
//  Created by dllo on 15/10/27.
//  Copyright (c) 2015年 赵连鹏. All rights reserved.
//

#import "ZLPTopicViewController.h"
#import <AFNetworking.h>
#import "ZLPMyTopicCell.h"
#import "ZLPFirstViewCell.h"
#import "ZLPDataModel.h"
#import "ZLPProductModel.h"
#import <UIImageView+WebCache.h>
#import "ZLPDetailViewController.h"
#import "ZLPResultDetailViewController.h"
#import "ZLPDataBaseHandle.h"
//#import "ZLPIsLoginHandle.h"


@interface ZLPTopicViewController ()<UITableViewDataSource, UITableViewDelegate, ZLPMyTopicCellDelegate>

@property(nonatomic, retain) UITableView *tableView;
@property(nonatomic, retain) NSMutableArray *headViewArr;
@property(nonatomic, retain) NSMutableArray *tableViewArr;
@property(nonatomic, retain) NSMutableArray *picArr;
@property(nonatomic, retain) UIImageView *imageView;
@property(nonatomic, retain) UILabel *textLabel;
@property(nonatomic, retain) UILabel *titleLabel;
@property(nonatomic, retain) UIView *myView;

@end

@implementation ZLPTopicViewController

- (void)dealloc {
    [_myView release];
    [_picArr release];
    [_titleLabel release];
    [_imageView release];
    [_textLabel release];
    [_tableViewArr release];
    [_tableView release];
    [_headViewArr release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"专题详情";
    
    // 创建tableView
    [self createTableView];
    
    // 创建view放在tableView的headerView上
    [self createMyView];

    
//    [self createData];
    
    [self isWlan];
    
    
   
    
    
}

- (void)isWlan {
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (status == 2 || status == 1) {
            
           
            
            SelectTopic result = [[ZLPDataBaseHandle shareDataBaseHandle] isHaveInTable:self.topic];
            if (result == InTable) {
                self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"collected.png"] style:UIBarButtonItemStylePlain target:self action:@selector(loveAction:)];
            } else if (result == NotInTable) {
                self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"collect.png"] style:UIBarButtonItemStylePlain target:self action:@selector(loveAction:)];
            } else {
                NSLog(@"Error");
            }
            
        } else {
            
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert show];
            
            UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
            image.image = [UIImage imageNamed:@"outnetwork.png"];
            [self.view addSubview:image];
            [image release];
            
            
        }
        
    }];
}

- (void)loveAction:(UIBarButtonItem *)button {
    
//    if ([ZLPIsLoginHandle shareZLPIsLoginHandle].isLogin) {
    
        if ([button.image isEqual:[UIImage imageNamed:@"collected.png"]]) {
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"取消收藏" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            
            [[ZLPDataBaseHandle shareDataBaseHandle] deleteTopicInDB:self.topic];
//            NSLog(@"~!!!~%@", [ZLPIsLoginHandle shareZLPIsLoginHandle].userName);
            
            button.image = [UIImage imageNamed:@"collect.png"];
        } else {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            
            [[ZLPDataBaseHandle shareDataBaseHandle] saveTopicInDB:self.topic];
//            NSLog(@"~!!~%@", [ZLPIsLoginHandle shareZLPIsLoginHandle].userName);
            
            button.image = [UIImage imageNamed:@"collected.png"];
//        }
//        
//    } else {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请先登陆" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alert show];
    }
    
    
    
}


#pragma mark createTableView
- (void)createTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 14) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.showsVerticalScrollIndicator = NO;
    
    [self createData];
}
#pragma mark createMyView
- (void)createMyView {
    self.myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 300)];
    self.tableView.tableHeaderView = self.myView;
    [_myView release];
    
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 150)];
    [self.myView addSubview:self.imageView];
    [_imageView release];
    
    self.textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 150, WIDTH, 150)];
    [self.myView addSubview:self.textLabel];
    self.textLabel.numberOfLines = 0;
    [_textLabel release];
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 120, WIDTH, 20)];
    [self.imageView addSubview:self.titleLabel];
    self.titleLabel.textColor = [UIColor whiteColor];
    [_titleLabel release];
    
}
#pragma markCreateData
- (void)createData {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:[NSString stringWithFormat:@"http://open3.bantangapp.com/topic/info?app_installtime=1445349591.654459&app_versions=4.2.2&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&id=%@&oauth_token=8e93baa2127b39cbf64d15bfee8cff56&os_versions=9.0.1", self.numID] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary *dic = responseObject;
        
        self.headViewArr = [NSMutableArray array];
        ZLPDataModel *model = [[ZLPDataModel alloc] init];
        [model setValuesForKeysWithDictionary:dic[@"data"]];
        [self.headViewArr addObject:model];
        
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:model.pic] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
        self.titleLabel.text = model.title;
        self.textLabel.text = model.desc;
        
        
        self.tableViewArr = [NSMutableArray array];
        self.tableViewArr = [ZLPProductModel baseModelByArr:dic[@"data"][@"product"]];
        
        
        
        [self.tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@", error);
        
    }];
    
    
    
    
}

- (void)click:(ZLPProductModel *)model {
    ZLPDetailViewController *detailVC = [[ZLPDetailViewController alloc] init];
    [self.navigationController pushViewController:detailVC animated:YES];
    
    detailVC.url = model.url;
}

#pragma mark TableView的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.tableViewArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuse = @"reuse";
    ZLPMyTopicCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[ZLPMyTopicCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
    }
    
    ZLPProductModel *model = [[ZLPProductModel alloc] init];
    model = self.tableViewArr[indexPath.row];
    cell.titleLabel.text = model.title;
    cell.descLabel.text = model.desc;
    cell.descLabel.numberOfLines = 0;
    cell.priceLabel.text = [NSString stringWithFormat:@"￥%@", model.price];
    
    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:model.pic[0][@"pic"]] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    
    cell.delegate = self;
    cell.model = self.tableViewArr[indexPath.row];
    
    return cell;
    
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    ZLPDetailViewController *detailVC = [[ZLPDetailViewController alloc] init];
//    [self.navigationController pushViewController:detailVC animated:YES];
//    
//    ZLPProductModel *model = [[ZLPProductModel alloc] init];
//    model = self.tableViewArr[indexPath.row];
//    
//    detailVC.url = model.url;
    
    ZLPResultDetailViewController *detailVC = [[ZLPResultDetailViewController alloc] init];
    [self.navigationController pushViewController:detailVC animated:YES];
    
    ZLPProductModel *model = [[ZLPProductModel alloc] init];
    model = self.tableViewArr[indexPath.row];
    
    detailVC.numID = model.numID;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZLPProductModel *model = [[ZLPProductModel alloc] init];
    model = self.tableViewArr[indexPath.row];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16], NSFontAttributeName, nil];
    CGRect rect = [model.desc boundingRectWithSize:CGSizeMake(375, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect.size.height + 463;
}



- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    return @"精选";
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 24)];
    headView.backgroundColor = [UIColor whiteColor];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 24)];
    [headView addSubview:label];
    [label release];
    
    UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH / 2 - 130, 12, 80, 3)];
    [headView addSubview:leftLabel];
    leftLabel.backgroundColor = [UIColor grayColor];
    [leftLabel release];
    
    UILabel *rightLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH / 2 + 50, 12, 80, 3)];
    [headView addSubview:rightLabel];
    rightLabel.backgroundColor = [UIColor grayColor];
    [rightLabel release];
    
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"糖  衣  精  选";
    label.textColor = [UIColor grayColor];
    
    return headView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
